//
//  EmoticonViewController.swift
//  表情键盘的搭建
//
//  Created by 简康达 on 16/6/16.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
 let emoticonCellID = "emoticonCellID"
class EmoticonViewController: UIViewController {
//    懒加载属性
    private lazy var packageManager : PackageManager = PackageManager()
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    private lazy var toolBar : UIToolbar = UIToolbar()
    var callBack : (emoticon:Emoticon) -> ()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.redColor()
        setupUI()
    }
    //MARK:- 重写构造函数
    init(callBack:(emoticon:Emoticon)->()){
        self.callBack = callBack
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// MARK:- UI相关设置
extension EmoticonViewController {
    func setupUI(){
//        添加控件
        view.addSubview(collectionView)
        view.addSubview(toolBar)
//        设置frame 
        collectionView.backgroundColor = UIColor.init(white: 0.95, alpha: 1.0)
        toolBar.backgroundColor = UIColor.lightGrayColor()
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        let views = ["collectionView":collectionView,"toolBar":toolBar]
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options: [.AlignAllLeft,.AlignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
//        布局collectionView
        collectionView.dataSource = self
        collectionView.delegate = self
//        注册cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: emoticonCellID)
//        布局toolBar
        prepareForToolBar()
    }
}
//MARK:- 布局toolBar
extension EmoticonViewController{
    func prepareForToolBar(){
//        定义数据
        let titles = ["最近","默认","Emoji","浪小花"]
        var items = [UIBarButtonItem]()
        items.append(UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil))
//        遍历数组，创建barButtonItem
        for i in 0..<titles.count {
            let item = UIBarButtonItem(title: titles[i], style: .Plain, target: self, action: #selector(EmoticonViewController.emoticonBtnClick))
//            设置文字颜色
            item.tintColor = UIColor.orangeColor()
            item.tag = i
            items.append(item)
//            添加弹簧
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(flexibleSpace)
        }
        items.removeLast()
        items.append(UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil))
//        将items赋值给toolBar的items数组
        toolBar.items = items
        
    }
    @objc private func emoticonBtnClick(item:UIBarButtonItem){
//        获取点击的indexPath所在组
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
//        滚到对应位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
}
//MARK:- 遵守collectionView协议 实现数据源方法
extension EmoticonViewController:UICollectionViewDataSource{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packageManager.packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = packageManager.packages[section]
        return package.emoticon.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//        创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCellID, forIndexPath: indexPath) as! EmoticonViewCell
//        给cell设置数据
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        let package = packageManager.packages[indexPath.section]
        cell.emoticon = package.emoticon[indexPath.row]
//        返回cell
        return cell
    }
}
//MAEK:- 遵守collectionView协议 实现代理方法
extension EmoticonViewController : UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let package = packageManager.packages[indexPath.section]
        let emoticon = package.emoticon[indexPath.row]
        insertRecentlyEmoticon(emoticon)
        callBack(emoticon: emoticon)
        
    }
    func insertRecentlyEmoticon(emoticon:Emoticon) {
//        判断是否是删除按钮或者站位表情
        if emoticon.isEmpty || emoticon.isRemove {
            return
        }
//       判断是否已经包含改表情
        if packageManager.packages[0].emoticon.contains(emoticon){
//            拿到改表情对应的index
            let index = (packageManager.packages[0].emoticon.indexOf(emoticon))!
//            删除对应的表情
            packageManager.packages[0].emoticon.removeAtIndex(index)
        }else{
            packageManager.packages[0].emoticon.removeAtIndex(19)
        }
        packageManager.packages[0].emoticon.insert(emoticon, atIndex: 0)
    }
}
//MARK: 自定义Layout
class EmoticonLayout: UICollectionViewFlowLayout{
    override func prepareLayout() {
        super.prepareLayout()
        //    定义常量
        let cols : CGFloat = 7
        let imageWH = UIScreen.mainScreen().bounds.width / cols
        //    设置布局
       itemSize = CGSize(width: imageWH, height: imageWH)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal
//        设置collectionView属性
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.pagingEnabled = true
        let insetMargin = ((collectionView?.frame.height)! - 3 * imageWH) / 2
        collectionView?.contentInset = UIEdgeInsetsMake(insetMargin, 0, insetMargin, 0)
    }
}